package com.djl.configuration;

import com.djl.annotation.Repository;
import com.djl.transaction.TransactionManager;
import org.mybatis.spring.mapper.ClassPathMapperScanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.*;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@Import(MybatisConfiguration.AutoConfiguredMapperScannerRegistrar.class)
public class MybatisConfiguration {


    /*
     * 声明事务管理器
     * 通过Primary注解强制声明为默认事务管理器
     * */
    @Bean(name = "transactionManager")
    @Primary
    public PlatformTransactionManager regTransactionManager() {
        return TransactionManager.acquireTransactionManager();
    }

    /**
     * 扫描类
     */
    static class AutoConfiguredMapperScannerRegistrar implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware {

        private static final Logger logger = LoggerFactory.getLogger(com.djl.configuration.MybatisConfiguration.AutoConfiguredMapperScannerRegistrar.class);

        private BeanFactory beanFactory;

        private DataSource dataSource;

        private ResourceLoader resourceLoader;

        @Override
        public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

            logger.info("Mybatis 默认扫描注解： @com.djl.annotation.Repository");
            logger.info("Mybatis 默认扫描包：com");
            ClassPathMapperScanner scanner = new com.djl.configuration.ClassPathMapperScanner(registry);

            try {
                if (this.resourceLoader != null) {
                    scanner.setResourceLoader(this.resourceLoader);
                }
                scanner.setAnnotationClass(Repository.class);
                scanner.registerFilters();
                scanner.doScan("com");
            } catch (IllegalStateException ex) {
                logger.debug("Could not determine auto-configuration package, automatic mapper scanning disabled.", ex);
            }
        }

        @Override
        public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
            this.beanFactory = beanFactory;
        }

        @Override
        public void setResourceLoader(ResourceLoader resourceLoader) {
            this.resourceLoader = resourceLoader;
        }

    }

}
